/* global window */
import { message } from 'antd'
import api from 'api'
import modelExtend from 'dva-model-extend'
import { pathMatchRegexp } from 'utils'
import { pageModel } from 'utils/model'
// import axios from 'axios'
import fetchJsonp from 'fetch-jsonp'

const {
  devices,
  projects,
  projectrename,
  queryuser,
  disputer,
  reproject,
  newproject,
  deleteproject,
  getdevicesoperate,
  //admins:
  deleteimeidevices,
  createdevice,
  movetorb,
  rbrestore,
  //workers
  projectGetWorkers,
  projectSetWorkers,
  projectSetCanAdd,
  Set_Light,
  setMode,
  // getProjectCanAdd,
} = api

const regionstate = {
  currentItem: {},
  modalVisible: false,
  modalType: 'create',
  selectedRowKeys: [],
  projects: [],
  choosedproject: 'all',
  modelusers: [],
  distributeresult: undefined,
  reprojectresult: undefined,
  deleteresult: undefined,
  createresult: undefined,
  movetorbresult: undefined,
  projectmodalVisible: false,
  deletemodalVisible: false,
  createmodalVisible: false,
  movetorbmodalVisible: false,
  devicesoperate: {},
  filter: {},
  canedit: false,
  //
  workers: [],
  workerModalVisible: false,
  workerSetWorkerresult: undefined,

  createProjectVisible: false,
  geoinputsuggestions: [],
  editingproject: undefined,
  // chooseprojectCanAdd: false,
  // createProjectresult: undefined,
}

export default modelExtend(pageModel, {
  namespace: 'devices',

  state: {
    ...regionstate,
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        if (
          pathMatchRegexp('/devices', location.pathname) ||
          pathMatchRegexp('/loras', location.pathname)
        ) {
          let payload = { page: 1, pageSize: 10, project: 'all' }
          if (location.query) {
            const { page, pageSize, project, filter } = location.query
            payload = {
              ...payload,
              ...(page != undefined && pageSize != undefined
                ? { page, pageSize }
                : {}),
              ...(project != undefined ? { project } : {}),
              ...(filter ? { filter: JSON.parse(filter) } : {}),
            }
          }
          dispatch({
            type: 'query',
            payload,
          })
          // dispatch({
          //   type: 'projectGetWorkers',
          //   payload: {
          //     projectid: payload.project,
          //   },
          // })
          dispatch({
            type: 'chooseproject',
            payload: payload.project,
          })
          dispatch({
            type: 'updateState',
            payload: {
              // selectedRowKeys: [],
              filter: payload.filter,
            },
          })
        }
      })
    },
  },

  effects: {
    *clearstore({ payload = {} }, { call, put, select }) {
      yield put({
        type: 'updateState',
        payload: {
          ...regionstate,
        },
      })
    },
    *Set_Light({ payload }, { call, put, select }) {
      message.loading('设置中...', 0)
      yield call(Set_Light, payload)
      message.destroy()
      message.success('设置成功')
    },
    *setMode({ payload }, { call, put, select }) {
      message.loading('提交中...', 0)
      yield call(setMode, payload)
      message.destroy()
      message.success('已提交操作，请等待响应')
    },
    *projectSetCanAdd({ payload }, { call, put, select }) {
      message.loading('修改中...', 0)
      yield call(projectSetCanAdd, payload)
      message.destroy()
      message.success('修改成功')
    },
    *convertPoint({ payload }, { call, put, select }) {
      const { lng, lat } = payload
      return fetchJsonp(
        `http://api.map.baidu.com/geoconv/v1/?coords=${lng},${lat}&from=1&to=5&ak=eDchGyK8ACCw7KSUpCXg96rq43I3TXGM`,
        {
          mode: 'no-cors',
          // credentials: 'include',
          headers: { Accept: 'application/json' },
          jsonCallbackFunction: 'showLocation',
        }
      ).then(response => response.json())
    },
    *queryInputGeo({ payload }, { call, put, select }) {
      const { lng, lat } = payload
      return fetchJsonp(
        `http://api.map.baidu.com/geoconv/v1/?coords=${lng},${lat}&from=1&to=5&ak=eDchGyK8ACCw7KSUpCXg96rq43I3TXGM`,
        {
          mode: 'no-cors',
          // credentials: 'include',
          headers: { Accept: 'application/json' },
          jsonCallbackFunction: 'showLocation',
        }
      ).then(response => response.json())
    },
    *InputGeosuggestion({ payload }, { call, put, select }) {
      // const { value } = payload
      if (payload && payload != '') {
        return fetchJsonp(
          `http://api.map.baidu.com/place/v2/suggestion?query=${payload}&region=全国&city_limit=false&output=json&ak=eDchGyK8ACCw7KSUpCXg96rq43I3TXGM`,
          {
            mode: 'no-cors',
            // credentials: 'include',
            headers: { Accept: 'application/json' },
            jsonCallbackFunction: 'showLocation',
          }
        ).then(response => response.json())
      }
    },
    *initdevicesoperate({ payload = {} }, { call, put, select }) {
      const { result } = yield call(getdevicesoperate, payload)
      yield put({
        type: 'updateState',
        payload: {
          devicesoperate: result,
        },
      })
    },
    *projectGetWorkers({ payload = {} }, { call, put, select }) {
      const { result } = yield call(projectGetWorkers, payload)
      yield put({
        type: 'updateState',
        payload: {
          workers: result,
        },
      })
    },
    *projectSetWorkers({ payload = {} }, { call, put, select }) {
      const { workerids } = payload
      const { choosedproject } = yield select(_ => _.devices)
      const { result } = yield call(projectSetWorkers, {
        ...payload,
        projectid: choosedproject,
      })
      yield put({
        type: 'updateState',
        payload: {
          workerSetWorkerresult: result,
        },
      })
    },
    *query({ payload = {} }, { call, put }) {
      const { result } = yield call(devices, payload)
      if (result && result.data != undefined) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: result.data,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: result.total,
            },
          },
        })
        yield put({
          type: 'updateState',
          payload: { selectedRowKeys: [], canedit: result.canedit },
        })
      }
    },
    *projects({ payload }, { call, put }) {
      const data = yield call(projects, payload)
      // const { success, message, status, ...other } = data.result
      // console.log(JSON.stringify(data));
      yield put({
        type: 'projectsSuccess',
        payload: {
          data: data.result.data,
        },
      })
    },
    *projectrename({ payload }, { call, put }) {
      message.loading('修改中...', 0)
      yield call(projectrename, payload)
      message.destroy()
      message.success('修改成功')
      yield put({
        type: 'updateState',
        payload: {
          createProjectVisible: false,
        },
      })
    },
    *reproject({ payload }, { call, put }) {
      message.loading('修改中...', 0)
      const data = yield call(reproject, payload)
      yield put({
        type: 'updateState',
        payload: { reprojectresult: data.result },
      })
      message.destroy()
      message.success('修改成功')
    },
    *rbrestore({ payload }, { call, put }) {
      message.loading('恢复中...', 0)
      yield call(rbrestore, payload)
      message.destroy()
      message.success('恢复成功')
    },
    *movetorb({ payload }, { call, put }) {
      const { result } = yield call(movetorb, payload)
      yield put({ type: 'updateState', payload: { movetorbresult: result } })
    },
    *newproject({ payload }, { call, put }) {
      message.loading('新建项目:' + payload.ProjectName, 0)
      yield call(newproject, payload)
      message.destroy()
      message.success('新建成功')
      yield put({
        type: 'updateState',
        payload: {
          createProjectVisible: false,
        },
      })
    },
    *deleteproject({ payload }, { call, put }) {
      message.loading('删除项目:' + payload.ProjectName, 0)
      yield call(deleteproject, payload)
      message.destroy()
      message.success('删除成功')
    },
    *deleteimeidevices({ payload }, { call, put }) {
      message.loading('删除中...', 0)
      const data = yield call(deleteimeidevices, payload)
      yield put({ type: 'updateState', payload: { deleteresult: data.result } })
      message.destroy()
      message.success('已申请系统删除，请稍后刷新页面查看结果！')
    },
    *createdevice({ payload }, { call, put }) {
      message.loading('设备新建中...', 0)
      yield call(createdevice, payload)
      // yield put({ type: 'updateState', payload: { createresult: data.result } })
      message.destroy()
      message.success('新建成功')
    },
    *finduser({ payload }, { call, put }) {
      const data = yield call(queryuser, payload)
      // yield put({ type: "queryuserssuccess", payload: data.result });
      yield put({ type: 'updateState', payload: { modelusers: data.result } })
    },
    *distribute({ payload }, { call, put }) {
      const data = yield call(disputer, payload)
      yield put({
        type: 'updateState',
        payload: { distributeresult: data.result },
      })
    },
    *showprojectmodal({ payload }, { select, call, put }) {
      yield put({
        type: 'updateState',
        payload: { reprojectresult: undefined, projectmodalVisible: true },
      })
    },
    *hideprojectmodal({ payload }, { select, call, put }) {
      yield put({
        type: 'updateState',
        payload: { reprojectresult: undefined, projectmodalVisible: false },
      })
    },
    *showdeletemodal({ payload }, { select, call, put }) {
      yield put({
        type: 'updateState',
        payload: { deleteresult: undefined, deletemodalVisible: true },
      })
    },
    *hidedeletemodal({ payload }, { select, call, put }) {
      yield put({
        type: 'updateState',
        payload: { deleteresult: undefined, deletemodalVisible: false },
      })
    },
    *showcreatemodal({ payload }, { select, call, put }) {
      yield put({
        type: 'updateState',
        payload: { createresult: undefined, createmodalVisible: true },
      })
    },
    *hidecreatemodal({ payload }, { select, call, put }) {
      yield put({
        type: 'updateState',
        payload: { createresult: undefined, createmodalVisible: false },
      })
    },

    *showmovetorbmodal({ payload }, { select, call, put }) {
      yield put({
        type: 'updateState',
        payload: { movetorbresult: undefined, movetorbmodalVisible: true },
      })
    },
    *hidemovetorbmodal({ payload }, { select, call, put }) {
      yield put({
        type: 'updateState',
        payload: { movetorbresult: undefined, movetorbmodalVisible: false },
      })
    },
  },

  reducers: {
    showModal(state, { payload }) {
      // console.log("call showModal");
      return {
        ...state,
        ...payload,
        distributeresult: undefined,
        modalVisible: true,
      }
    },
    showWorkerModal(state, { payload }) {
      return {
        ...state,
        ...payload,
        workerSetWorkerresult: undefined,
        workerModalVisible: true,
      }
    },
    showcreateProjectModal(state, { payload }) {
      return {
        ...state,
        ...payload,
        createProjectVisible: true,
      }
    },
    hideModal(state) {
      return {
        ...state,
        modelusers: [],
        distributeresult: undefined,
        workerSetWorkerresult: undefined,
        modalVisible: false,
        workerModalVisible: false,
        createProjectVisible: false,
        editingproject: undefined,
      }
    },

    projectsSuccess(state, { payload }) {
      const { data } = payload
      state.projects = data
    },
    chooseproject(state, { payload }) {
      state.choosedproject = payload
    },
    queryuserssuccess(state, { payload }) {
      state.modelusers = payload
    },
  },
})
